import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';
import { FriendStatus } from '@/app/types/friend';

export async function GET(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const friendships = await prisma.friend.findMany({
      where: {
        status: FriendStatus.ACCEPTED,
        OR: [{ userId: userId }, { friendId: userId }],
      },
      include: {
        user: true,
        friend: true,
      },
    });

    const friends = friendships.map((friendship) => {
      const friendUser = friendship.userId === userId ? friendship.friend : friendship.user;
      return {
        id: friendUser.id,
        username: friendUser.username,
        nickname: friendUser.nickname,
        avatar: friendUser.avatar,
        bio: friendUser.bio,
        friendshipId: friendship.id,
      };
    });

    return NextResponse.json(friends);
  } catch (error) {
    console.error('获取好友列表失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}